package testJdk.nio.testSeclector.selectorServerDemo;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @author cyd
 * @version 1.0.0
 * @date 2021/11/24 11:31
 */


public class ClientDemo {

    /**
     * 向服务端建立SocketChannel通道
     * 并发布三次selectionKey，按照顺序分别是：OP_ACCEPT、OP_READ、OP_WRITE
     */
    @Test
    public void client01() throws IOException {
        SocketChannel sc = SocketChannel.open();
        // 1.当sc连接上时，服务端的selectionKey变成 OP_ACCEPT
        sc.connect(new InetSocketAddress("127.0.0.1", 8000));

        ByteBuffer outBuffer = ByteBuffer.allocate(32);
        ByteBuffer inBuffer = ByteBuffer.allocate(32);

        outBuffer.put("hello , i am 01".getBytes());
        outBuffer.flip();

        Charset charset = Charset.forName("UTF-8");


//        while (true) {
        outBuffer.rewind();
        // 2.向服务端写入，此时服务端的selectionKey变成 OP_READ
        sc.write(outBuffer);
        inBuffer.clear();

        // 3.从服务端读取，此时服务端的selectionKey变成 OP_WRITE
        sc.read(inBuffer);
        inBuffer.flip();
        System.out.println(Charset.forName("UTF-8").decode(inBuffer));
        inBuffer.clear();
//        }
    }

    @Test
    public void client02() throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("127.0.0.1", 8000));

        ByteBuffer outBuffer = ByteBuffer.allocate(32);
        ByteBuffer inBuffer = ByteBuffer.allocate(32);

        outBuffer.put("hello , i am 02".getBytes());
        outBuffer.flip();

        while (true) {
            outBuffer.rewind();
            // 向服务端写入
            sc.write(outBuffer);
            inBuffer.clear();

            // 从服务端读取
            sc.read(inBuffer);
            inBuffer.flip();
            System.out.println(Charset.forName("UTF-8").decode(inBuffer));
        }
    }


}
